<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;

class Taskjob extends Command
{

    protected function configure()
    {
        $this
            // 命令的名字（"think" 后面的部分）
            ->setName('app:task-job')
            // 运行 "php think list" 时的简短描述
            ->setDescription('task job Statistics')
            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp("This command allows you to task job Statistics...");
    }

    protected function execute(Input $input, Output $output)
    {
        while (true) {
            // 输出多行到控制台（每一行的末尾添加 "\n"）
            $ids = Db::name('task_job')
                ->where('callstate', 'success')
                ->where('count_status', '0')
                ->where('completed', '1')
                ->order('updatetime desc')
                ->limit(200)
                ->column('id');

            foreach ($ids as $id) {
                $output->writeln('[' . date('Y-m-d H:i:s', time()) . ']  INFO   [faseadmin] start task_job_id = ' . $id);
                $this->update_task_job_grade($id);
                $output->writeln('[' . date('Y-m-d H:i:s', time()) . ']  INFO  [faseadmin] task_job_id = ' . $id);
            }
//            $output->writeln('[' . date('Y-m-d H:i:s', time()) . ']  INFO  [faseadmin]  任务执行结束');
            sleep(10);
        }

    }

    private function update_task_job_grade($job_id)
    {
        $this->load_task_job_detail_json($job_id);
        $this->count_task_job_detail($job_id);
    }

    private function load_task_job_detail_json($job_id)
    {
        if (Db::name('task_job_detail')->where('task_job_id', $job_id)->count() == 0) {
            $path = Env::get('speech_script_output_path', '') . '/' . $job_id . '.json';
            if (file_exists($path)) {
                $json_str = file_get_contents($path);
                $data = json_decode($json_str, true);
                foreach ($data['flow_result'] as $d) {
                    $value = array('task_job_id' => $job_id,
                        'type' => $d['type'],
                        'flow_name' => $d['flow_name'],
                        'hint' => is_null($d['voice']['hint']) ? " " : $d['voice']['hint'],
                        'path' => array_key_exists('path', $d['voice']) == null ? "" : $d['voice']['path'],
                        'addtime' => $d['voice']['time']);
                    if (Db::name('task_job_detail')->where($value)->count() == 0) {
                        Db::name('task_job_detail')->insert($value);
                    }
                }
            }
        }
    }


    private function count_task_job_detail($job_id)
    {
//        echo $job_id."</br>";
        if (Db::name('task_job_detail')->where('task_job_id', $job_id)->count() > 0) {
            $routernum = Db::name('task_job_detail')->where('task_job_id', $job_id)->where('type', 'robot')->count();
            $humannum = Db::name('task_job_detail')->where('task_job_id', $job_id)->where('type', 'human')->count();
            $faqnum = $this->count_task_faq_num($job_id);

            //通话时长
            $taskcalltime = Db::name('cdr')
                ->where(['caller_id_number' => 'JOB' . $job_id])
                ->where('billsec', '>', 0)
                ->value('billsec');

            if ($taskcalltime == 0) {
                $taskcalltime = Db::name('task_job_detail')->where('task_job_id', $job_id)->max('addtime') -
                    Db::name('task_job_detail')->where('task_job_id', $job_id)->min('addtime');
            }


            $task_id = Db::name('task_job')->where('id', $job_id)->value('tid');
            //如果客户不说话，直接评级为D
            if ($humannum == 0) {
                $grade = "D";
            } else {
                $grade = $this->set_grade($task_id, $taskcalltime, $faqnum);
            }

            if ($grade == 'A') {
                $this->send_wechat($job_id);
            }
            Db::name('task_job')->where('id', $job_id)->update(
                array("routernum" => $routernum,
                    "faqnum" => $faqnum,
                    "taskcalltime" => $taskcalltime,
                    "grade" => $grade,
                    'count_status' => '1'
                ));
        } else {
            Db::name('task_job')->where('id', $job_id)->update(
                array("routernum" => 0,
                    "faqnum" => 0,
                    "taskcalltime" => 0,
                    "grade" => 'D',
                    'count_status' => '1'
                ));
        }
    }

    private function count_task_faq_num($job_id)
    {
        $num = 0;
        $task_id = Db::name('task_job')->where('id', $job_id)->value('tid');
        $speech_id = Db::name('task')->where('id', $task_id)->value('speech_id');
        $keywords = Db::name('speech_faq')->where('speech_id', $speech_id)->where('important', 1)->column('keyword');
        $faqs = Db::name('task_job_detail')->where('task_job_id', $job_id)
            ->where('type', 'human')->where('flow_name', 'faq')->select();
        foreach ($faqs as $faq) {
            $hint = $faq['hint'];
            foreach ($keywords as $keyword) {
                $keys = explode(',', $keyword);
                foreach ($keys as $key) {
                    if ($key != '') {
                        if (strstr($hint, $key)) {
                            $num += 1;
                            break;
                        }
                    }
                }

            }
        }
        return $num;
    }

    private function set_grade($task_id, $taskcalltime, $faqnum)
    {
//        var_dump($task_id);
        $val = "D";

        try {

            $speech_id = Db::name('task')->where('id', $task_id)->value('speech_id');
            echo 'speech_id sql = '.Db::name('')->getLastSql()."\r\n";
            $grades = Db::name('speech_grade')->where('speech_id', $speech_id)->select();
            echo 'grades sql = '.Db::name('')->getLastSql()."\r\n";
            if ($grades == null) {
                $grade = new \app\admin\controller\speech\Grade();
                $grade->init($speech_id);
                $grades = Db::name('speech_grade')->where('speech_id', $speech_id)->select();
            }


            $vals = array();
            foreach ($grades as $grade) {
                $vals[$grade['name']] = ['calltime' => $grade['calltime'], 'faqnum' => $grade['faqnum']];
            }
            if (($vals['C类客户']['calltime'] > 0 and $taskcalltime >= $vals['C类客户']['calltime'])
                or ($vals['C类客户']['faqnum'] > 0 and $faqnum >= $vals['C类客户']['faqnum'])) {
                $val = "C";
            }
            if (($vals['B类客户']['calltime'] > 0 and $taskcalltime >= $vals['B类客户']['calltime'])
                or ($vals['B类客户']['faqnum'] > 0 and $faqnum >= $vals['B类客户']['faqnum'])) {
                $val = "B";
            }
            if (($vals['A类客户']['calltime'] > 0 and $taskcalltime >= $vals['A类客户']['calltime'])
                or ($vals['A类客户']['faqnum'] > 0 and $faqnum >= $vals['A类客户']['faqnum'])) {
                $val = "A";
            }
        } catch (Exception $e) {
            ;
        }
        return $val;
    }

    public function send_wechat($job_id)
    {

        $wechat = new \app\admin\controller\wechat\Index();

        $totalWx = Db::name('task_wx')
            ->alias('w')
            ->join('task_job j', 'j.tid = w.tid')
            ->join('task t', 'w.tid = t.id ')
            ->join('speech_faq f', 'j.faqnum = f.id', 'left')
            ->where('j.id', $job_id)
            ->field('w.openid,t.name as task_name,j.name,j.number,j.record_path,f.keyword')
            ->find();


        if ($totalWx) {
            $url=str_replace('/usr/share/nginx/html/public', 'http://data.vanxtec.com', $totalWx['record_path']);
            $url=str_replace('/tmp/rebot', 'https://data.vanxtec.com', $url);
            if ($wechat->sendMsg($totalWx['openid'], $totalWx['name'], "A类客户", $totalWx['number'], $totalWx['task_name'], $url, $totalWx['keyword'])) {
                Log::info('推送微信消息，job_id:' . $job_id . '客户电话：' . $totalWx['number']);
            }
        }

    }




}
